#include "task_queue.h"
#include <stdio.h>
#include <stdlib.h>

int task_queue_empty(task_queue_t *task_queue) { return task_queue->size == 0; }

task_queue_t *task_queue_create() {
  task_queue_t *task_queue = (task_queue_t *)calloc(1, sizeof(task_queue_t));
  if (!task_queue) {
    perror("calloc");
  }
  return task_queue;
}

int task_enqueue(task_queue_t *task_queue, int netfd) {
  task_t *task = (task_t *)calloc(1, sizeof(task_t));
  if (!task) {
    perror("calloc");
  }

  task->netfd = netfd;

  if (task_queue_empty(task_queue)) {
    task_queue->front = task;
    task_queue->rear = task;
    ++task_queue->size;
    return 0;
  }

  task_queue->rear->next = task;
  task_queue->rear = task;
  ++task_queue->size;

  return 0;
}

int task_dequeue(task_queue_t *task_queue) {
  if (task_queue_empty(task_queue))
    return 0;

  task_t *cur = task_queue->front;
  task_queue->front = cur->next;
  free(cur);
  --task_queue->size;
  return 0;
}
